<template>
  <div class="login-page">
    <div class="header">
      <img src="@/assets/logo.svg" alt="冷库自助下单系统" class="logo" />
      <h1>冷库自助下单系统</h1>
    </div>

    <van-form @submit="handleSubmit">
      <van-cell-group inset>
        <!-- 手机号输入 -->
        <van-field
          v-model="loginForm.phone"
          type="tel"
          label="手机号"
          placeholder="请输入手机号"
          clearable
          :rules="phoneRules"
        />

        <!-- 密码输入 -->
        <van-field
          v-model="loginForm.password"
          :type="passwordVisible ? 'text' : 'password'"
          label="密码"
          placeholder="请输入密码"
          clearable
          :rules="passwordRules"
        >
          <!-- 密码可见性切换 -->
          <template #right-icon>
            <van-icon
              :name="passwordVisible ? 'eye-o' : 'closed-eye'"
              @click.stop="passwordVisible = !passwordVisible"
            />
          </template>
        </van-field>

        <!-- 验证码 -->
        <div class="captcha-container" v-if="showCaptcha">
          <van-field
            v-model="loginForm.captcha"
            label="验证码"
            placeholder="请输入验证码"
            :rules="[{ required: true, message: '请输入验证码' }]"
          />
          <canvas ref="captchaCanvas" class="captcha-canvas" @click="generateCaptcha"></canvas>
        </div>
      </van-cell-group>

      <div class="submit-btn">
        <van-button
          round
          block
          type="primary"
          native-type="submit"
          :loading="isLoggingIn"
          loading-text="登录中..."
        >
          登录
        </van-button>
      </div>
    </van-form>

    <div class="footer-links">
      <router-link to="/register">注册账号</router-link>
      <router-link to="/forgot-password">忘记密码</router-link>
    </div>

    <!-- 其他登录方式 -->
    <div class="other-login">
      <van-divider>其他登录方式</van-divider>
      <div class="login-methods">
        <div class="login-method" @click="handleWechatLogin">
          <van-icon name="wechat" class="wechat-icon" />
          <span>微信登录</span>
        </div>
        <div class="login-method" @click="showSmsLogin = true">
          <van-icon name="comment" class="sms-icon" />
          <span>短信登录</span>
        </div>
      </div>
    </div>

    <!-- 短信登录弹窗 -->
    <van-popup v-model:show="showSmsLogin" round position="bottom" :style="{ height: '50%' }">
      <div class="sms-login-popup">
        <van-form @submit="handleSmsLogin">
          <van-cell-group inset>
            <van-field
              v-model="smsForm.phone"
              type="tel"
              label="手机号"
              placeholder="请输入手机号"
              :rules="phoneRules"
            />

            <van-field
              v-model="smsForm.captcha"
              center
              clearable
              label="短信验证码"
              placeholder="请输入验证码"
              :rules="[{ required: true, message: '请输入验证码' }]"
            >
              <template #button>
                <van-button
                  size="small"
                  type="primary"
                  plain
                  @click="sendSms"
                  :disabled="countdown > 0"
                >
                  {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
                </van-button>
              </template>
            </van-field>
          </van-cell-group>

          <div class="submit-btn">
            <van-button round block type="primary" native-type="submit"> 登录 </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>
  </div>
</template>

<script lang="ts">
import { Toast, Notify } from 'vant'
import { defineComponent, reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
// import { getUserInfoAPI } from '../stores/user'

interface LoginForm {
  phone: string
  password: string
  captcha?: string
}

interface SmsLoginForm {
  phone: string
  captcha: string
}

export default defineComponent({
  name: 'LoginPage',

  setup() {
    const router = useRouter()
    const userStore = useUserStore()

    // 登录表单数据
    const loginForm = reactive<LoginForm>({
      phone: '',
      password: '',
      captcha: '',
    })

    // 短信登录表单数据
    const smsForm = reactive<SmsLoginForm>({
      phone: '',
      captcha: '',
    })

    // 状态变量
    const isLoggingIn = ref(false)
    const passwordVisible = ref(false)
    const showCaptcha = ref(false)
    const captchaCode = ref('')
    const captchaCanvas = ref<HTMLCanvasElement | null>(null)
    const showSmsLogin = ref(false)
    const countdown = ref(0)

    // 验证规则
    const phoneRules = [
      { required: true, message: '请输入手机号' },
      { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' },
    ]

    const passwordRules = [
      { required: true, message: '请输入密码' },
      { min: 6, max: 20, message: '密码长度在6-20位之间' },
      { pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/, message: '密码需包含字母和数字' },
    ]

    // 生成验证码
    const generateCaptcha = () => {
      if (!captchaCanvas.value) return

      const ctx = captchaCanvas.value.getContext('2d')
      if (!ctx) return

      // 清空画布
      ctx.clearRect(0, 0, 100, 38)

      // 生成随机验证码
      const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz123456789'
      let code = ''
      for (let i = 0; i < 4; i++) {
        code += chars.charAt(Math.floor(Math.random() * chars.length))
      }
      captchaCode.value = code

      // 绘制验证码
      ctx.fillStyle = '#f5f5f5'
      ctx.fillRect(0, 0, 100, 38)

      ctx.font = 'bold 24px Arial'
      ctx.fillStyle = '#333'

      // 添加随机旋转和位移
      for (let i = 0; i < code.length; i++) {
        ctx.save()
        const x = 15 + i * 20
        const y = 28
        const rot = (Math.random() - 0.5) * 0.4

        ctx.translate(x, y)
        ctx.rotate(rot)
        ctx.fillText(code[i], -8, 8)
        ctx.restore()
      }

      // 添加干扰线
      ctx.strokeStyle = '#ccc'
      for (let i = 0; i < 5; i++) {
        ctx.beginPath()
        ctx.moveTo(Math.random() * 100, Math.random() * 38)
        ctx.lineTo(Math.random() * 100, Math.random() * 38)
        ctx.stroke()
      }
    }

    // 登录处理
    const handleSubmit = async () => {
      isLoggingIn.value = true

      try {
        // 密码登录
        await userStore.login({
          phone: loginForm.phone,
          password: loginForm.password,
          captcha: showCaptcha.value ? loginForm.captcha : undefined,
        })

        Toast({ message: '登录成功', icon: 'success' })
        router.push('/')
      } catch (error) {
        if (typeof error === 'string' && error.includes('验证码')) {
          showCaptcha.value = true
          generateCaptcha()
        }
        Notify({ type: 'danger', message: error instanceof Error ? error.message : '登录失败' })
      } finally {
        isLoggingIn.value = false
      }
    }

    // 短信登录处理
    const handleSmsLogin = async () => {
      try {
        await userStore.smsLogin({
          phone: smsForm.phone,
          smsCode: smsForm.captcha,
        })

        Toast({ message: '登录成功', icon: 'success' })
        router.push('/')
        showSmsLogin.value = false
      } catch (error) {
        Notify({ type: 'danger', message: error instanceof Error ? error.message : '登录失败' })
      }
    }

    // 发送短信验证码
    const sendSms = async () => {
      // 验证手机号
      if (!smsForm.phone || !/^1[3-9]\d{9}$/.test(smsForm.phone)) {
        Toast('请输入正确的手机号')
        return
      }

      try {
        // 调用发送短信API
        await userStore.sendSmsCode(smsForm.phone)

        // 开始倒计时
        countdown.value = 60
        const timer = setInterval(() => {
          countdown.value--
          if (countdown.value <= 0) {
            clearInterval(timer)
          }
        }, 1000)

        Toast('验证码已发送')
      } catch (error) {
        Notify({
          type: 'danger',
          message: error instanceof Error ? error.message : '发送验证码失败',
        })
      }
    }

    // 微信登录
    const handleWechatLogin = () => {
      // 实际项目中应调用微信登录API
      Toast('正在调用微信登录...')

      // 模拟微信登录成功
      setTimeout(() => {
        Toast({ message: '微信登录成功', icon: 'success' })
        router.push('/')
      }, 1500)
    }

    // 组件挂载时生成验证码
    onMounted(() => {
      generateCaptcha()
    })

    return {
      loginForm,
      smsForm,
      isLoggingIn,
      passwordVisible,
      showCaptcha,
      captchaCanvas,
      showSmsLogin,
      countdown,
      phoneRules,
      passwordRules,
      generateCaptcha,
      handleSubmit,
      handleSmsLogin,
      sendSms,
      handleWechatLogin,
    }
  },
})
</script>

<style scoped lang="scss">
.login-page {
  padding: 30px 20px;
}

.header {
  text-align: center;
  margin-bottom: 40px;

  .logo {
    width: 80px;
    height: 80px;
    border-radius: 10px;
    background-color: #f0f4ff;
    padding: 10px;
    box-sizing: border-box;
  }

  h1 {
    font-size: 24px;
    margin-top: 15px;
    color: #333;
    font-weight: 600;
  }
}

.captcha-container {
  display: flex;
  align-items: center;
  padding: 0 16px;

  .captcha-canvas {
    width: 100px;
    height: 38px;
    border: 1px solid #eee;
    border-radius: 4px;
    cursor: pointer;
    margin-left: 10px;
  }
}

.submit-btn {
  margin: 30px 16px;
}

.footer-links {
  margin-top: 30px;
  display: flex;
  justify-content: space-between;
  padding: 0 20px;

  a {
    color: #1989fa;
    text-decoration: none;
    font-size: 14px;
  }
}

.other-login {
  margin-top: 40px;

  .login-methods {
    display: flex;
    justify-content: center;
    gap: 40px;

    .login-method {
      display: flex;
      flex-direction: column;
      align-items: center;
      color: #666;
      font-size: 14px;
      cursor: pointer;

      &:hover {
        opacity: 0.8;
      }

      .van-icon {
        font-size: 36px;
        margin-bottom: 8px;
      }

      .wechat-icon {
        color: #07c160;
      }

      .sms-icon {
        color: #1989fa;
      }
    }
  }
}

.sms-login-popup {
  padding: 20px;

  .submit-btn {
    margin-top: 20px;
  }
}
</style>
